<template>

</template>

<script>
import {getUserInfo} from "@/utils/owninfo";
import {getToken} from "@/utils/auth";

export default {
  name: "Websocket",
  data() {
    return {
      socket: null,
      userid:'10',
      message:'',
    }
  },
  created() {
    if(getToken()!=="undefined"){
      this.open(getUserInfo())
    }
  },
  mounted() {
    this.$mybus.on('openWebsocket',data=>{
      console.log(data); //控制台输出接收到的数据
      // this.$message.success(data)
      this.open(data)
    })
  },
  methods: {
    open: function openSocket(userid) {
      this.userid = userid;
      const that = this
      if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      }
      else{
        console.log("您的浏览器支持WebSocket");
        var socketUrl="http://localhost:8190/message/imserver/"+this.userid;
        socketUrl=socketUrl.replace("https","ws").replace("http","ws");
        console.log(socketUrl);
        if(this.socket!=null){
          this.socket.close();
          this.socket=null;
        }
        this.socket = new WebSocket(socketUrl);
        //打开事件
        this.socket.onopen = function() {
          console.log("websocket已打开");
          //socket.send("这是来自客户端的消息" + location.href + new Date());
        };
        //获得消息事件
        this.socket.onmessage = function(msg) {
          // console.log("来消息");

          const data = JSON.parse(msg.data)
          console.log(data.body);
          // console.log(data.body.message);
          //发现消息进入    开始处理前端触发逻辑
          if(data.type === "message"){
            that.$message.success(data.body.user.username+"发来信息:"+data.body.message.messagebody)
            that.$mybus.emit('addMessage',data.body);
          }else if(data.type === "notice"){
            //data.body.notice.sendtype+"发来通知"
            that.$message.success(data.body.notice.body)
            that.$mybus.emit('addNotice',data.body.notice);
          }
        };
        //关闭事件
        this.socket.onclose = function() {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        this.socket.onerror = function() {
          console.log("websocket发生了错误");
        }
      }
    },
    sendMessage: function sendMessage(message) {
      this.message = message
      if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      }else {
        console.log("您的浏览器支持WebSocket");
        // console.log('{"toUserId":"'+this.userid+'","contentText":"'+this.message+'"}');
        // this.socket.send('{"toUserId":"'+this.userid+'","contentText":"'+this.message+'"}');
      }
    }
  }
}
</script>

<style scoped>

</style>
